#!/user/bin/env python
# -*-coding:utf-8-*-
'''
@author: Patty
@project: automation_framework
@file: authority.py
@time: 2019/8/20  15:52
@IDE: PyCharm 
'''

from util.string_util import  random_char
from util.db_util import execute_query
import base.globalvars as glo
import logging


def get_auth_appid(name):
    results = execute_query("SELECT id FROM `t_permission_app` WHERE `name`='%s'" % name)
    try:
        result = results[0][0]
        return result
    except Exception as e:
        logging.error("no result retrieved")
        return None


def get_auth_userid(name, type, dbname='DB'):
    results = execute_query(
        "SELECT id FROM `t_permission_user` WHERE `username`='%s' AND account_type=%d" % (name, type), dbname=dbname)
    try:
        result = results[0][0]
        return result
    except Exception as e:
        logging.error("no result retrieved")
        return None


def get_auth_permissionid(appname, permissionname):
    results = execute_query(
        "SELECT permission.id FROM `t_permission_app` as app JOIN t_permission_permission as permission ON app.id=permission.app_id WHERE app.name='%s' AND permission.`name`='%s'" % (
            appname, permissionname))
    try:
        result = results[0][0]
        return result
    except Exception as e:
        logging.error("no result retrieved")
        return None


def get_auth_roleid(appname, rolename):
    results = execute_query(
        "SELECT role.id FROM `t_permission_app` as app JOIN t_permission_role as role ON app.id=role.app_id WHERE app.name='%s' AND role.`name`='%s'" % (
            appname, rolename))
    try:
        result = results[0][0]
        return result
    except Exception as e:
        logging.error("no result retrieved")
        return None


def Generate_str(type, len):
    if type == 'appName':
        results = 'app测试' + random_char(len)
        glo.set_value("authAppName", results)
    elif type == 'appId':
        results = 'apptest' + random_char(len)
    elif type == 'userName':
        results = 'user_' + random_char(len)
        glo.set_value("authUserName", results)
    elif type == 'email':
        results = random_char(8) + '@test.com'
        glo.set_value("authEmail", results)
    else:
        logging.error("not request type")
    try:
        result = results[:]
        return result
    except Exception as e:
        logging.error("no result retrieved")
        return None
